package com.luck;

import com.luck.api.UserManager;
import com.luck.email.EmailInfo;
import com.luck.email.MailConfig;
import com.luck.email.MailService;
import com.luck.model.po.Users;
import com.luck.rabbit.RabbitSend;
import com.luck.common.Constant;
import com.luck.common.Encryption;
import com.luck.common.UserConstant;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.*;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Hua wb on 2018/6/14.
 */
@Controller
@RequestMapping("/user")
@Api(tags = "用户管理相关接口")
@Slf4j
public class UserController {
    @Autowired
    private UserManager userManager;
    @Autowired
    private RabbitSend rabbitSend;
    @Autowired
    private MailService mailService;

    @RequestMapping("/")
    public ModelAndView getUsers(Users users){
        ModelAndView modelAndView = new ModelAndView();
        List<Users> userList = userManager.getUserList(users);
        modelAndView.setViewName("/user/usersInfo");
        modelAndView.addObject("users", userList);
        return modelAndView;
    }
    @GetMapping("/{id}")
    @ApiOperation("获取用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true)
    })
    public ModelAndView getUser(@PathVariable("id") int id){
        ModelAndView modelAndView = new ModelAndView();
        Users users = userManager.getUsers(id);
        modelAndView.setViewName("userInfo");
        modelAndView.addObject("users", users);
        return modelAndView;
    }

    /**
     * 用户注册
     * 需要激活邮箱账户
     * @param users
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("用户注册")
    public String addUser(Users users, @RequestParam("file") MultipartFile file){
        users.setStatus(UserConstant.USER_STATUS_FROZEN);
        userManager.insert(users);
        String token = Encryption.MD5(String.valueOf(users.getUserId()));
        users.setToken(token);
        userManager.updateUsersToken(users);
        EmailInfo emailInfo = new EmailInfo();
        emailInfo.setTo(users.getEmail());
        emailInfo.setSubject(MailConfig.SUBJECT_REGISTER);
        emailInfo.setContent(String.valueOf(users.getUserId()));
        Map map = new HashMap(2);
        map.put("name", users.getName());
        map.put("host", Constant.INDEX + "user/userActivate/" + token);
        emailInfo.setMap(map);
        emailInfo.setTemplatePath("mailTemplateActivate.ftl");
        mailService.sendMail(emailInfo);
        // todo ecs未安装rabbitMq
        // rabbitSend.sendMessage(JSONObject.toJSONString(emailInfo), RabbitConfig.ROUTING_KEY_EMAIL);
        return "redirect:/";
    }

    @RequestMapping("/userActivate/{token}")
    public ModelAndView userActivate(@PathVariable("token") String token) {
        int i = userManager.updateActivate(token);
        ModelAndView modelAndView = new ModelAndView("explain");
        String message = "激活成功!";
        if (i <= 0) {
            message = "激活失败!";
        }
        modelAndView.addObject("message", message);
        modelAndView.addObject("host", Constant.INDEX);
        return modelAndView;
    }

    /**
     * 用户登录
     * 将登陆信息存入session
     * user:用户名、userId:用户Id
     * @param users
     * @param httpSession
     * @return
     */
    @RequestMapping("/loginCheck")
    public ModelAndView loginCheck(Users users, HttpSession httpSession){
        return loginUtil(users, httpSession);
    }

    /**
     * 游客登录
     * @param httpSession
     * @return
     */
    @RequestMapping("/loginTourist")
    public ModelAndView loginTourist(HttpSession httpSession){
       return loginUtil(null, httpSession);
    }

    private ModelAndView loginUtil(Users users, HttpSession httpSession){
        ModelAndView modelAndView = new ModelAndView("redirect:/");
        String userName = "游客";
        int userId = 1;
        if (users != null) {
            String phone = users.getPhone();
            String pwd = users.getPwd();
            users = userManager.checkUser(phone, pwd);
            if (users != null) {
                userName = users.getName();
                userId = users.getUserId();
            } else {
                return modelAndView;
            }
        }
        httpSession.setAttribute(Constant.SESSION_USER, userName);
        httpSession.setAttribute(Constant.SESSION_USER_ID, userId);
        return modelAndView;
    }

    /**
     * 用户删除
     * @param request
     * @zasdasaa
     */
    @RequestMapping("/del/")
    @ResponseBody
    public String delUser(HttpServletRequest request){
        String id = request.getParameter("id");
        userManager.delUser(Integer.parseInt(id));
        return "redirect:/";
    }
}
